#!/usr/bin/env python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api.labs import taskqueue
from schema import *

import logging

class RankCounter(webapp.RequestHandler):
  def post(self):
    PAGESIZE = 50
    next = None
    computationid = long(self.request.get("computationid"))
    total = self.request.get("total")
    if total.isdigit():
      total = int(total)
    else:
      total = 0
    logging.debug("I'll count ranks for computation %i." % computationid)
    computation = RankComputation.get_by_id(computationid)
    logging.debug("The computation key is %s." % str(computation.key()))
    bookmark = self.request.get("rank_key")
    logging.debug("The rank key is %s." % bookmark)
    
    ranks = DocumentRank.all().order("__key__")
    computation_ranks = ranks.filter("computationid =", computationid)
    if bookmark:
      logging.debug("This is a continuation.")
      logging.debug("The last batch left off with %s." % bookmark)
      next_ranks = computation_ranks.filter('__key__ >=', db.Key(bookmark))
      batch_of_ranks = next_ranks.fetch(PAGESIZE+1)
    else:
      logging.debug("This is the first batch.")
      batch_of_ranks = computation_ranks.fetch(PAGESIZE+1)

      # Rank pages
      body = '<form action="/rank-nodes" method="POST">'
      body += '<input type="hidden" name="computationid" value="'
      body += str(computationid) + '" />'
      body += '<input type="submit" value="Rank" /></form>'
      self.response.out.write("<html><body>%s</body></html>" % body)
    
    logging.debug("This batch has %i ranks." % len(batch_of_ranks))
    
    logging.debug("Now I'll count some ranks.")
    total += len(batch_of_ranks)
    
    if len(batch_of_ranks) == PAGESIZE+1:
      logging.debug("There are enough ranks for another batch.")
      next = batch_of_ranks[-1]
      total -= 1
      logging.debug("The next batch starts with rank %s." % str(next.key()))
      task = taskqueue.Task(
        url='/count-ranks',
        params={
          'computationid': str(computationid),
          'rank_key': str(next.key()),
          'total': str(total),
        }
      )
      task.add(queue_name='parse')
    else:
      computation.node_count = total
      computation.put()


def main():
  logging.getLogger().setLevel(logging.DEBUG)
  wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
    ('/count-ranks', RankCounter),
  ]))


if __name__ == '__main__':
  main()
